/**
 *Copyright(c) HNA SYSTEMS Co., LTD
 *
 *@date 2013-7-10
 * 	
 *Original Author: 郑兴(zhengxing)
 *
 *ChangeLog
 *
 */
package com.hnas.sys.core.filter;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hnas.sys.core.util.InjectKeyCheckUtils;

/**
 * 
 * @author 郑兴(zhengxing)
 * 
 */
public class InjectFilter implements Filter {
	private Logger log = LoggerFactory.getLogger(InjectFilter.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig arg0) throws ServletException {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@SuppressWarnings("rawtypes")
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain filterChain) throws IOException, ServletException {
		// log.debug("...Perform inject filter...");
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		Map parameters = request.getParameterMap();

	/*	if (isExcludeUrls(request.getRequestURI())) {
			// 不需要过滤的网址处理
			filterChain.doFilter(request, response);
		} else {
			String injeckKey = InjectKeyCheckUtils.hasInjectKeys(parameters);
			if (StringUtil.isNotEmpty(injeckKey)) {
				log.debug("Request parameters has inject key [" + injeckKey + "]");
				response.sendRedirect(request.getContextPath() + "/illegalOperation.jsp");
			} else {
				filterChain.doFilter(request, response);
			}
		}*/
//		Map parameters = request.getParameterMap();		
		boolean backend = request.getRequestURI().startsWith(request.getContextPath()+"/backend/");
		//非法字符
				if(isExcludeUrls(request.getRequestURI())){
					//不需要过滤的网址处理
					
				}
				else
				{
					String refer = request.getHeader("REFERER");
//					if (null==refer || !InjectKeyCheckUtils.isValidRefer(refer)){//非法访问
////						response.sendRedirect(request.getContextPath() + "/illegalOperation.jsp?type=4");
//						if (request.getRequestURI().indexOf("showOrderDetail")<0){
//							response.setStatus(403);
//							response.getWriter().close();
//							return ;
//						}
//					}
//					parameters.put("backend", backend);
					if (InjectKeyCheckUtils.hasInjectKeys(parameters,backend)) {
						
//						response.setContentType("text/html");
//						PrintWriter out = response.getWriter();
//						out.flush();				
//						out.print("很抱歉，你的输入中含有非法字符！");
//						out.flush();
//						out.close();	
//						return ;
						response.sendRedirect(request.getContextPath() + "/illegalOperation.jsp?type=1");
						return ;
//					}
//					?	response.sendRedirect(request.getContextPath() + "/error.jsp");
				} else {
					//filterChain.doFilter(request, response);
				}
				
			}	
				//字符长度
				if (parameters != null && parameters.size() > 0 && !isExcludeUrls(request.getRequestURI()) && !backend) {//非过滤url
					//判断字符长度
//					parameters.remove("backend");
					for (Iterator iter = parameters.keySet().iterator(); iter.hasNext();) {
						String key = (String) iter.next();
						String[] values = (String[]) parameters.get(key);
						for (int i = 0; i < values.length; i++) {
							// Only when length is greater than 15
							// url encoding,,,
							String inputValue = values[i];
							//判断字符长度，一般不超过50
							if (null!=inputValue){
								int length = inputValue.length(); 
							/*	String msg = null;
								if (length>50 && ",trf.remark,rpf.remark,".indexOf(key)<0){
									//提示
									msg = "字符过长（不能超过50个字符）：";//+inputValue;
								}else if (length>200 && ",trf.remark,rpf.remark,".indexOf(key)<0){
									//提示
									msg = "字符过长（不能超过200个字符）：";//+inputValue;
								}
								if (null!=msg){
									
//									response.setContentType("text/html");
//									PrintWriter out = response.getWriter();
//									out.flush();				
//									out.print("很抱歉，你输入的字符过长！");//+msg
//									out.flush();
//									out.close();	
//									return ;
									response.sendRedirect(request.getContextPath() + "/illegalOperation.jsp?type=2");
//								}
							}*/
								if (InjectKeyCheckUtils.isOverLength(key, length)){
									response.sendRedirect(request.getContextPath() + "/illegalOperation.jsp?type=2");
									return ;
								}
						}
					}
				}
			}
				filterChain.doFilter(request, response);
	}

	/**
	 * <pre>
	 * 过滤无需检查关键字的URL
	 * </pre>
	 * 
	 * @Auther 郑兴(zhengxing)
	 * @Date 2013-7-10
	 * @param url
	 * @return
	 */
	private boolean isExcludeUrls(String url) {
//		boolean result = false;
//		String[] excludeValues = new String[] { "/backend/" };
//		for (int i = 0; i < excludeValues.length; i++) {
//			if (url.indexOf(excludeValues[i]) > -1) {
//				return true;
//			}
//		}
//		return result;
		if (1==1)return true;
		return InjectKeyCheckUtils.isExcludeUrls(url);
	}
}
